import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Store } from '@ngrx/store';
import { State, UserState } from '../../store';
import * as fromUserState from '../../store/selectors/user.selector';
import { map } from 'rxjs/operators';

@Injectable()
export class UserValidatorGuard implements CanActivate {

  constructor(
    private store: Store<State>,
    private router: Router
  ) {}

  canActivate(): Observable<boolean> {
    return this.store.select(fromUserState.getUserState)
      .pipe(
        map((state: UserState) => {
          if(state.info && state.token) {
            return true;
          } else {
            this.router.navigate(['/login']);
            return false;
          }
        })
      );
  }
}
